Shortest Palindrome using KMP (LPS Array)
Finding the longest palindromic prefix to minimize prepended characters.
📝 Problem & KMP String Setup
The shortest palindrome is achieved by finding the **Longest Proper Prefix of $S$ that is already a palindrome**. This prefix should not need any characters prepended.
The KMP solution requires creating a special string $S'$:
($S$ = Original String, $S^R$ = Reversed String, $\#$ = Unique Separator)
Input Section
Concatenated String ($S'$):
💡 LPS Array Key Insight
The Goal: Find Longest Palindromic Prefix (LPP)
The LPP of $S$ is the longest prefix of $S$ that matches a suffix of $S^R$.
How LPS Helps:
- The KMP LPS array calculates the length of the longest **prefix** of $S'$ that is also a **suffix** of the current substring $S'[0\dots i]$.
- When computing the LPS array for $S' = S + \# + S^R$, the comparisons are effectively matching the prefix of $S$ (the prefix of $S'$) against a suffix of $S^R$ (the suffix of $S'$).
- The value of the **last element** of the LPS array, $\text{LPS}[|S'|-1]$, gives the length ($L$) of the longest prefix of $S$ that forms a palindrome with a suffix of $S$.
Construction Formula:
If the final $\text{LPS}$ value is $L$ (Length of Longest Palindromic Prefix), the characters that need to be prepended come from the beginning of $S^R$ (or the end of $S$).
🎬 Step-by-Step LPS Array Computation
String $S'$ and LPS Array $\pi$
**Current State:** Index $i=?$, LPS Pointer $\text{len}=?$
Output Log
🎉 Final Shortest Palindrome
The length of the Longest Palindromic Prefix (LPP) is the final value of the LPS array:
$L = \text{LPS}[|S'|-1] = ?$
Characters to Prepend
Characters required: $|S| - L = ? - ? = ?$ characters.